package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.tool.ToolClient;
import com.fwtai.web.StoreAreaDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 门店管理业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @Email service@fwtai.com
 * @创建日期 2023-09-20 17:10:29
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class StoreAreaService{

  private final StoreAreaDao storeAreaDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public StoreAreaService(final StoreAreaDao storeAreaDao,final ThreadPoolTaskExecutor taskExecutor){
    this.storeAreaDao = storeAreaDao;
    this.taskExecutor = taskExecutor;
  }

  public String listAreaUsers(final String word){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(word == null || word.length() <= 0){
          return ToolClient.jsonCode198("请输入关键字搜索");
        }
        return ToolClient.queryJson(storeAreaDao.listAreaUsers(word));
      } catch (final Exception ignored){
        return ToolClient.exceptionJson();
      }
    },taskExecutor).join();
  }

  //换绑
  public String edit(final Long userId,final Long target){
    //若用到ThreadLocal的数据可在此组装
    return CompletableFuture.supplyAsync(()->{
      if(userId == null || target == null){
        return ToolClient.jsonValidateField();
      }
      final String code = storeAreaDao.getUserCode(target);
      if(code == null){
        return ToolClient.createJsonFail("指定的区代不存在");
      }
      final PageFormData formData = new PageFormData();
      formData.put("kid",userId);
      formData.put("invitation_code",code);
      return ToolClient.executeRows(storeAreaDao.updateCode(formData),"操作成功","换绑失败,刷新重试");
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> storeAreaDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> storeAreaDao.getListTotal(formData),taskExecutor);
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}